#pragma once
#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

const int backlog = 10; // 全连接队列

enum
{
    SocketErr = 2,
    BindErr,
    ListenErr,
    NonBlockErr
};

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

    // 创建套接字
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            cerr << "socket failed,errno" << errno << " ,err string" << strerror(errno) << endl;
            exit(SocketErr);
        }

        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    // 绑定ip和端口号
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            cerr << "bind failed,errno" << errno << " ,err string" << strerror(errno) << endl;
            exit(BindErr);
        }
    }

    // 设置监听套接字
    void Listen()
    {
        if (listen(_sockfd, backlog) < 0)
        {
            cerr << "listen failed,errno" << errno << " ,err string" << strerror(errno) << endl;
            exit(ListenErr);
        }
    }

    // 参数为输出型参数
    int Accept(string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int newfd = accept(_sockfd, (struct sockaddr *)&client, &len);
        if (newfd < 0)
        {
            cerr << "accept failed,errno" << errno << " ,err string" << strerror(errno) << endl;
            return -1;
        }
        char ip_str[64];
        inet_ntop(AF_INET, &client.sin_addr, ip_str, sizeof(ip_str));
        *clientip = ip_str;
        *clientport = ntohs(client.sin_port);

        return newfd;
    }

    bool Connect(uint16_t serverport, string &serverip)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());

        socklen_t len = sizeof(server);
        if (connect(_sockfd, (struct sockaddr *)&server, len) < 0)
        {
            cerr << "connect failed,errno" << errno << " ,err string" << strerror(errno) << endl;
            return false;
        }

        return true;
    }

    void Close()
    {
        close(_sockfd);
    }
    
    int Fd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};